from PIL import Image
from PIL.ExifTags import TAGS
import binascii
import os
import xlwt


def task_1(saveimagefolderpath):
	"""
	获取图像gps并保存为excel文件
	:param saveimagefolderpath:
	:return:
	"""
	workbook = xlwt.Workbook(encoding='utf-8')
	sheet1 = workbook.add_sheet("测试表格")
	sheet1.write(0, 0, "经度")  # 第1行第1列数据
	sheet1.write(0, 1, "纬度")  # 第1行第2列数据
	sheet1.write(0, 2, "图像名称")  # 第1行第2列数据
	imagenamefilelist = os.listdir(saveimagefolderpath)
	folderpath, foldername = os.path.split(saveimagefolderpath)
	excelfilename = foldername + r".xls"
	excelfilepath = os.path.join(folderpath, excelfilename)
	for index, imagename in enumerate(imagenamefilelist):
		imagefilepath = os.path.join(saveimagefolderpath, imagename)
		lat, lon = testForExif(imagefilepath)
		sheet1.write(index+1, 0, lon)
		sheet1.write(index+1, 1, lat)
		sheet1.write(index+1, 2, imagename)
	workbook.save(excelfilepath)
	return


def testForExif(imgfilepath):
	"""
	获取图像的GPS属性
	:param imgfilepath:
	:return:
	"""
	imgFile = Image.open(imgfilepath)
	info = imgFile._getexif()
	lattuple = info[34853][2]
	lontuple = info[34853][4]
	lat = lattuple[0] + lattuple[1] / 60 + lattuple[2] / 3600
	lon = lontuple[0] + lontuple[1] / 60 + lontuple[2] / 3600
	return float(lat), float(lon)




if __name__ == '__main__':
	saveimagefolderpath = r"E:\Yang\宁波杨梅\12.21宁波杨梅\汇头村无人机照片"
	# excelfilepath = r"E:\Yang\宁波杨梅\12.21宁波杨梅\LonLat.xls"
	task_1(saveimagefolderpath)
    # testForExif(r'E:\Yang\宁波杨梅\12.21宁波杨梅\梅溪村无人机照片\DJI_0504.JPG')

